package com.jiaoyou.baojian;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;

import com.alibaba.sdk.android.push.CommonCallback;
import com.jiaoyou.baojian.activity.BangActivity;
import com.jiaoyou.baojian.activity.BaseActivity;
import com.jiaoyou.baojian.activity.CreateUserInfoActivity;
import com.jiaoyou.baojian.activity.LoginRegActivity;
import com.jiaoyou.baojian.activity.MineActivity;
import com.jiaoyou.baojian.adapter.MainActivityPagerAdapter;
import com.jiaoyou.baojian.agora.AgoraHelper;
import com.jiaoyou.baojian.constvalue.ConstValue;
import com.jiaoyou.baojian.dialog.OkDialog;
import com.jiaoyou.baojian.dialog.YesOrNoDialog;
import com.jiaoyou.baojian.entity.CallResponse;
import com.jiaoyou.baojian.entity.GlobalSettingEntity;
import com.jiaoyou.baojian.entity.UserDetail;
import com.jiaoyou.baojian.http.Api;
import com.jiaoyou.baojian.http.BaofangCallback;
import com.jiaoyou.baojian.otto.Event;
import com.jiaoyou.baojian.utils.Utils;
import com.jiaoyou.baojian.wiget.UnScrollableViewPager;
import com.lhh.apst.library.AdvancedPagerSlidingTabStrip;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloader;
import com.squareup.otto.Subscribe;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;

public class MainActivity extends BaseActivity {

    @BindView(R.id.tabs)
    AdvancedPagerSlidingTabStrip tabs;
    @BindView(R.id.viewpager)
    UnScrollableViewPager viewpager;
    @BindView(R.id.bangdan)
    ImageView bangdan;
    @BindView(R.id.wo)
    ImageView wo;
    //    @BindView(R.id.my_toolbar)
//    Toolbar my_toolbar;
    private MainActivityPagerAdapter mainPagerAdapter;

    private Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);

//        setSupportActionBar(my_toolbar);
        setTitle(getString(R.string.app_name));

        viewpager.setPagingEnabled(true);
        mainPagerAdapter = new MainActivityPagerAdapter(getSupportFragmentManager());
        viewpager.setAdapter(mainPagerAdapter);
        tabs.setViewPager(viewpager);
        tabs.getTabAt(0).setSelected(true);
        tabs.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                for(int i = 0; i < mainPagerAdapter.getCount(); i++){
                    tabs.getTabAt(i).setSelected(false);
                }
                tabs.getTabAt(position).setSelected(true);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        needOtto();
        AgoraHelper.getInstance().setupMainActivity(this);
        BaojianApplication.getInstance().pushService.clearNotifications();
        checkUpdate();
    }

    @Override
    public void onResume() {
        super.onResume();

        if(AgoraHelper.getInstance().agoraAPI.isOnline() == 0 && Utils.isLogin()){
            //信令登录因未知原因被断开，自动重新登录
            //TODO clear toast
            toast("信令登录因未知原因被断开，自动重新登录中...");
            final String account = getLoginResponse().user.id + "";
            AgoraHelper.getInstance().agoraAPI.login(ConstValue.AGORA_APPID, account, Utils.getAgoraToken(account), 0, "");
//            Api.getInstance().getLoginKey(account, new BaofangCallback<CallResponse>() {
//                @Override
//                public void onFailure(Call call, Throwable t) {
////                    toast("网络错误，请稍后重试");
//                    finish();
//                    getHandler().postDelayed(new Runnable() {
//                        @Override
//                        public void run() {
//                            System.exit(0);
//                        }
//                    }, 1000);
//                }
//
//                @Override
//                public void onSuccess(CallResponse res) {
//                    AgoraHelper.getInstance().agoraAPI.login(ConstValue.AGORA_APPID, account, res.agoraSignalingKey, 0, "");
//                }
//            });
        }
    }

    private void checkUpdate() {
        GlobalSettingEntity.AndroidUpdateInfo updateInfo =
                getGson().fromJson(getACache().getAsString("update"), GlobalSettingEntity.AndroidUpdateInfo.class);
        if(updateInfo == null)
            return;
        if(updateInfo.versionCode <= BuildConfig.VERSION_CODE){
            Log.i("检查更新", "当前已是最新版");
            return;
        }
        Log.i("检查更新", "发现更新");
        String path = getExternalCacheDir().getAbsolutePath() + "/update/" + updateInfo.versionCode + ".apk";
        final File file = new File(path);
        if(!file.exists()){
            //不存在，下载
            Log.i("检查更新", "开始下载更新包，强制wifi环境才能下载，为用户节约流量");
            FileDownloader.getImpl().create(Utils.getImageUrl(this, updateInfo.path))
                    .setPath(getExternalCacheDir().getAbsolutePath() + "/update/" + updateInfo.versionCode + ".apk")
                    .addFinishListener(new BaseDownloadTask.FinishListener() {
                        @Override
                        public void over(BaseDownloadTask task) {
                            Log.i("检查更新", "新apk下载成功，下一次启动时提示更新");
                        }
                    })
                    .setWifiRequired(true)
                    .start();
            //等下一次启动app的时候引导安装
        } else {
            //apk已经存在，已经下载好了
            if (updateInfo.forceUpdate) {
                Log.i("检查更新", "强制更新");
                showOkDialog("强制更新：" + updateInfo.updateContent,
                        new OkDialog.OnClickListener() {
                            @Override
                            public void onBtnClick() {
                                Intent intent = new Intent(Intent.ACTION_VIEW);
                                intent.addCategory(Intent.CATEGORY_DEFAULT);
                                intent.setDataAndType(Uri.fromFile(file),
                                        "application/vnd.android.package-archive");
                                startActivity(intent);
                                finish();
                            }
                        });
                return;
            } else {
                Log.i("检查更新", "询问是否更新");
                showYesOrNoDialog("发现更新：" + updateInfo.updateContent, "取消", "更新",
                        new YesOrNoDialog.OnClickListener() {
                            @Override
                            public void onLeftClick() {

                            }

                            @Override
                            public void onRightClick() {
                                Intent intent = new Intent(Intent.ACTION_VIEW);
                                intent.addCategory(Intent.CATEGORY_DEFAULT);
                                intent.setDataAndType(Uri.fromFile(file),
                                        "application/vnd.android.package-archive");
                                startActivity(intent);
                            }
                        });
            }
        }
    }

    /**
     * 同步数据，以防一些意外情况
     * 没啥好同步的了，换方案了
     */
    public void initData() {
        if(!Utils.isLogin()){
            return;
        }
        if(TextUtils.isEmpty(getLoginResponse().userInfo.nickname)){
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    startActivity(CreateUserInfoActivity.class);
                }
            }, 1000);
        }
        Api.getInstance().getUserDetail(getLoginResponse().user.id, new BaofangCallback<UserDetail>() {
            @Override
            public void onFailure(Call call, Throwable t) {

            }

            @Override
            public void onSuccess(UserDetail userDetail) {
                getLoginResponse().update(MainActivity.this, userDetail);

            }
        });
        if(!getLoginResponse().actress) {
        }

        registerPush();
    }

    private void registerPush() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                BaojianApplication.getInstance().pushService.bindAccount("" + getLoginResponse().user.id,
                        new CommonCallback(){
                            @Override
                            public void onSuccess(String s) {
                                Log.d("MainActivity", "bindAccount success:" + s);
                            }

                            @Override
                            public void onFailed(String s, String s1) {
                                Log.d("MainActivity", "bindAccount failed:" + s + "/" + s1);
                            }
                        });
                BaojianApplication.getInstance().turnOnPush();
            }
        }, 1000);
    }

    @Override
    public int getContentView() {
        return R.layout.activity_main;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @OnClick({R.id.bangdan, R.id.wo})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bangdan:
                startActivity(BangActivity.class);
//                showImageSelectDialog(null);
                break;
            case R.id.wo:
                if(!Utils.isLogin()){
                    startActivity(LoginRegActivity.class);
                    return;
                }
                startActivity(MineActivity.class);
                break;
        }
    }

    @Subscribe
    public void onLogin(String data) {
        if(Event.EVENT_LOGIN_SUCCESS.equals(data)){
            toast("登录成功");

            registerPush();
        }
    }

    private long lastPressed;
    @Override
    public void onBackPressed() {
        long current = System.currentTimeMillis();
        if((current - lastPressed) > 500){
            toast("再按一次返回键退出");
            lastPressed = current;
            return;
        }
        super.onBackPressed();
    }

}
